package com.zbkj.crmeb.merchant.admin.controller;

import com.crmeb.core.common.CommonResult;
import com.common.PageParamRequest;
import com.constants.Constants;
import com.crmeb.core.exception.CrmebException;
import com.crmeb.core.exception.ExceptionCodeEnum;
import com.utils.ExcelUtil;
import com.utils.OSSUtil;
import com.zbkj.crmeb.chant.response.SupplierAccountCenterResponse.SupplierBill;
import com.zbkj.crmeb.chant.service.IChannelMerchantAccountService;
import com.zbkj.crmeb.export.vo.SupplierFlowExcelVo;
import com.zbkj.crmeb.export.vo.SupplierOrderExcelVo;
import com.zbkj.crmeb.export.vo.SupplierProductExcelVo;
import com.zbkj.crmeb.export.vo.UploadSupplierProductExcelVo;
import com.zbkj.crmeb.export.vo.UploadSupplierProductExcel2Vo;
import com.zbkj.crmeb.merchant.admin.service.SupplierStoreOrderService;
import com.zbkj.crmeb.merchant.admin.service.SupplierStoreProductService;
import com.zbkj.crmeb.store.model.StoreProductUpload;
import com.zbkj.crmeb.store.request.StoreOrderSearchRequest;
import com.zbkj.crmeb.store.request.SupplierStoreProductSearchRequest;
import com.zbkj.crmeb.store.response.StoreProductResponse;
import com.zbkj.crmeb.store.response.SupplierOrderItemResponse;
import com.zbkj.crmeb.store.service.StoreProductUploadService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;


/**
 * 供应商 Excel
 */
@Slf4j
@Controller
@RequestMapping("api/admin/supplier/excel")
@Api(tags = "供应商 -- Excel")
@RestController("SupplierExcelController")
public class SupplierExcelController extends AdminBaseController {

    @Autowired
    private SupplierStoreProductService supplierStoreProductService;
    @Autowired
    private SupplierStoreOrderService supplierStoreOrderService;
    @Autowired
    private StoreProductUploadService storeProductUploadService;
    @Autowired
    private IChannelMerchantAccountService channelMerchantAccountService;

    AtomicInteger atom = new AtomicInteger(0);
    final int max = 10;

//    @ApiOperation(value = "上传模板")
//    @PostMapping(value = "/upload/product/template")
//    public CommonResult<Object> uploadExcelTemplate(@RequestParam("file") MultipartFile file,HttpServletRequest request) {
//        try {
//            if(StringUtils.isBlank(file.getOriginalFilename())){
//                throw new CrmebException("文件名不能为空");
//            }
//            String excelType = OSSUtil.getExcelType(FilenameUtils.getExtension("." + file.getOriginalFilename()));
//            if (StringUtils.isEmpty(excelType)){
//                throw new CrmebException("文件格式不合法，必须为csv,xls,xlsx");
//            }
//            String fileName = file.getOriginalFilename();
//            String url = OSSUtil.uploadLocalExcel(Constants.UPLOAD_EXCEL_FILE_WAREHOUSE_DIR, file, fileName);
//            return CommonResult.success(url);
//        } catch (Exception e) {
//            throw new CrmebException(e.getMessage());
//        }
//    }

    @ApiOperation(value = "供应商excel上传商品")
    @PostMapping(value = "/upload/product")
    public CommonResult<Object> uploadExcel(@RequestParam("file") MultipartFile file,HttpServletRequest request) {
        try {
            if(StringUtils.isBlank(file.getOriginalFilename())){
                throw new CrmebException("文件名不能为空");
            }
            String excelType = OSSUtil.getExcelType(FilenameUtils.getExtension("." + file.getOriginalFilename()));
            if (StringUtils.isEmpty(excelType)){
                throw new CrmebException("文件格式不合法，必须为csv,xls,xlsx");
            }
            long millis = System.currentTimeMillis();
            InputStream inputStream = file.getInputStream();
            List<UploadSupplierProductExcelVo> list = ExcelUtil.importExcel(inputStream,UploadSupplierProductExcelVo.class);
            StoreProductUpload storeProductUpload = supplierStoreProductService.importProductList(list,getMerId(request));
            String fileName = file.getOriginalFilename();
            if(fileName.contains("-")){
                fileName = fileName.substring(fileName.lastIndexOf("-")+1);
            }
            String url = OSSUtil.uploadLocalExcel(Constants.UPLOAD_EXCEL_FILE_WAREHOUSE_DIR, file, millis+"-" + fileName);
            storeProductUpload.setTime(System.currentTimeMillis()-millis);
            storeProductUpload.setUrl(url);
            storeProductUpload.setResult(StringUtils.isBlank(url) ? 0 : 1);
            storeProductUploadService.updateById(storeProductUpload);
            return CommonResult.success(storeProductUpload.getMsg());
        } catch (Exception e) {
        	e.printStackTrace();
            throw new CrmebException(e.getMessage());
        }
    }

    //2023.02.20新增
    @ApiOperation(value = "供应商excel上传商品")
    @PostMapping(value = "/upload/product_2")
    public CommonResult<Object> uploadExcel2(@RequestParam("file") MultipartFile file,HttpServletRequest request) {
        try {
            if(StringUtils.isBlank(file.getOriginalFilename())){
                throw new CrmebException("文件名不能为空");
            }
            String excelType = OSSUtil.getExcelType(FilenameUtils.getExtension("." + file.getOriginalFilename()));
            if (StringUtils.isEmpty(excelType)){
                throw new CrmebException("文件格式不合法，必须为csv,xls,xlsx");
            }
            long millis = System.currentTimeMillis();
            InputStream inputStream = file.getInputStream();
            List<UploadSupplierProductExcel2Vo> list = ExcelUtil.importExcel(inputStream,UploadSupplierProductExcel2Vo.class);
            StoreProductUpload storeProductUpload = supplierStoreProductService.importProductList2(list,getMerId(request));
            String fileName = file.getOriginalFilename();
            if(fileName.contains("-")){
                fileName = fileName.substring(fileName.lastIndexOf("-")+1);
            }
            String url = OSSUtil.uploadLocalExcel(Constants.UPLOAD_EXCEL_FILE_WAREHOUSE_DIR, file, millis+"-" + fileName);
            storeProductUpload.setTime(System.currentTimeMillis()-millis);
            storeProductUpload.setUrl(url);
            storeProductUpload.setResult(StringUtils.isBlank(url) ? 0 : 1);
            storeProductUploadService.updateById(storeProductUpload);
            return CommonResult.success(storeProductUpload.getMsg());
        } catch (Exception e) {
            e.printStackTrace();
            throw new CrmebException(e.getMessage());
        }
    }

    @ApiOperation(value = "商品模板下载")
    @GetMapping(value = "/download/template/product")
    public CommonResult<String> downloadProductTemplate(HttpServletResponse response) {
        return CommonResult.success("https://italytao.oss-cn-shanghai.aliyuncs.com/product-warehouse-excel/template/product_import_template.xlsx", ExceptionCodeEnum.SUCCESS.getMessage());
//        return "https://italytao.oss-cn-shanghai.aliyuncs.com/product-warehouse-excel/product_import_template.xlsx";
//        List<UploadSupplierProductExcelVo> list = new ArrayList<>();
//        ExcelUtil.setSheetName("product");
//        ExcelUtil.setFileName("商品导入模板");
//        ExcelUtil.writeExcel(response, list, UploadSupplierProductExcelVo.class);
    }

    @ApiOperation(value = "供应商商品导出")
    @GetMapping(value = "/product")
    public void export(SupplierStoreProductSearchRequest request,HttpServletRequest httpServletRequest, HttpServletResponse response) {
        try {
            // 保护一下 最多允许10个人同时导出
            if (atom.getAndIncrement() < max) {
                request.setPage(Constants.DEFAULT_PAGE);
                request.setLimit(BooleanUtils.isTrue(request.getIsImg()) ? Constants.IMG_EXPORT_MAX_LIMIT : Constants.EXPORT_MAX_LIMIT);
                List<StoreProductResponse> productList = supplierStoreProductService.supplierProductList(request, getMerId(httpServletRequest)).getList();
                List<SupplierProductExcelVo> list = supplierStoreProductService.parseExportList(productList);
                //sheet名称
                ExcelUtil.setSheetName("product");
                //文件名称前缀
                ExcelUtil.setFileName("商品导出");
                ExcelUtil.writeExcelByIsImg(response, list, SupplierProductExcelVo.class,request.getIsImg());
            }
        } finally {
            atom.decrementAndGet();
        }
    }

    @ApiOperation(value = "供应商订单导出")
    @GetMapping(value = "/order")
    public void storeOrderexport(StoreOrderSearchRequest request, HttpServletRequest servletRequest, HttpServletResponse response) {
        try {
            // 保护一下 最多允许10个人同时导出
            if (atom.getAndIncrement() < max) {
                request.setMerId(getMerId(servletRequest));
                PageParamRequest pageParamRequest = new PageParamRequest();
                pageParamRequest.setPage(Constants.DEFAULT_PAGE);
                pageParamRequest.setLimit(Constants.EXPORT_MAX_LIMIT);
                List<SupplierOrderItemResponse> orderList = supplierStoreOrderService.orderList(request, pageParamRequest).getList().getList();
                List<SupplierOrderExcelVo> orderExcelVoList = supplierStoreOrderService.parseExportList(orderList,request.getMerId());
                //sheet名称
                ExcelUtil.setSheetName("订单信息表");
                //文件名称前缀
                ExcelUtil.setFileName("订单导出");
                ExcelUtil.writeExcelByIsImg(response, orderExcelVoList, SupplierOrderExcelVo.class, request.getIsImg());
            }
        } finally {
            atom.decrementAndGet();
        }
    }

    @ApiOperation(value = "供应商财务导出")
    @GetMapping(value = "/flow")
    public void supplierFlowExport(PageParamRequest pageParamRequest, HttpServletRequest servletRequest, HttpServletResponse response) {
        try {
            if (atom.getAndIncrement() < max) {
                pageParamRequest.setPage(Constants.DEFAULT_PAGE);
                pageParamRequest.setLimit(Constants.EXPORT_MAX_LIMIT);
                List<SupplierBill> billList = channelMerchantAccountService.supplierAccountCenter(getMerId(servletRequest), pageParamRequest).getOrderList().getList();
                List<SupplierFlowExcelVo> supplierExportList = channelMerchantAccountService.parseSupplierExportList(billList);
                //sheet名称
                ExcelUtil.setSheetName("财务信息");
                //文件名称前缀
                ExcelUtil.setFileName("财务导出");
                ExcelUtil.writeExcel(response, supplierExportList, SupplierFlowExcelVo.class);
            }
        } finally {
            atom.decrementAndGet();
        }
    }

}



